package com.matrix.draft.sockettest.groupchatroom.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class SocketBufferBroadcaster {
    public static void broadcast(List<SocketChannel> targetChannels, ByteBuffer buffer, SocketChannel fromChannel){
        // 被广播成功的channel
        List<SocketChannel> channelsDone = new ArrayList<>(targetChannels.size()-2);
        // 开始广播
        targetChannels.stream()
                .filter(target->!target.equals(fromChannel))
                .forEach(target->{
                    try {
                        target.write(buffer);
                        buffer.flip();
                        channelsDone.add(target);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
        // 日志
        StringBuffer sb= new StringBuffer("已广播给: ");
        channelsDone.stream().map(Object::hashCode).forEach(hashCode->sb.append(hashCode).append(","));
        System.err.println(new String(sb));
    }
}
